package com.huashi.dealer.modular.controller.store.dashboard.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.huashi.dealer.commonEntity.Order;
import com.huashi.dealer.core.component.DataScopeInfo;
import com.huashi.dealer.modular.business.order.mapper.OrderMapper;
import com.huashi.dealer.modular.business.user.mapper.UserMapper;
import com.huashi.dealer.modular.controller.store.dashboard.param.StoreDashboardResponse;
import com.huashi.dealer.modular.controller.store.dashboard.service.StoreDashboardService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class StoreDashboardServiceImpl implements StoreDashboardService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private DataScopeInfo dataScopeInfo;
    // 将聚合统计用SQL统一到 UserMapper.xml，避免多XML跨查

    @Override
    public StoreDashboardResponse getOverview(Long storeUserId, String startTime, String endTime, Integer limit) {
        // 解析时间
        String start = null;
        String end = null;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (startTime != null && !startTime.isEmpty()) {
            // 直接传字符串到XML，使用 UNIX_TIMESTAMP 解析
            start = startTime;
        }
        if (endTime != null && !endTime.isEmpty()) {
            end = endTime;
        }

        // 1) 计算可见用户ID列表（对应 PHP 的 getSpecifyUser）
        List<Long> visibleUserIds = getSpecifyUserIds(storeUserId);

//        List<Long> visibleUserIds= new ArrayList<>();
//        if (!dataScopeInfo.filter().contains(-1L)) {
//            visibleUserIds=dataScopeInfo.filter();
//        }
        // 2) 最新订单号列表
        List<Order> latestOrders = userMapper.selectLatestOrders(visibleUserIds, start, end, limit);

        // 3) 年度目标（经销商 sales_money 之和）
        BigDecimal salesMoney = userMapper.sumSalesMoney(visibleUserIds);

        // 4) 拿货金额（时间范围内订单实付合计）
        BigDecimal orderPrice = userMapper.sumOrderPayPrice(visibleUserIds, start, end);

        // 5) 基本账户充值合计
        BigDecimal balanceAll = userMapper.sumBalanceMoney(visibleUserIds, start, end);

        // 6) 打款单待审核数
        Integer applyNumber = userMapper.countBalanceApplyPending(visibleUserIds, start, end);

        // 7) 待审核订单总量
        Integer orderTotal = userMapper.countAuditOrders(visibleUserIds, start, end);

        // 8) 待发货订单总量
        Integer deliveryOrderTotal = userMapper.countDeliveryOrders(visibleUserIds, start, end);

        // 组装返回
        StoreDashboardResponse resp = new StoreDashboardResponse();

        StoreDashboardResponse.OrderBlock orderBlock = new StoreDashboardResponse.OrderBlock();
        List<StoreDashboardResponse.OrderNoItem> nos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(latestOrders)) {
            latestOrders.forEach(o -> {
                StoreDashboardResponse.OrderNoItem item = new StoreDashboardResponse.OrderNoItem();
                item.setOrderId(o.getOrderId().longValue());
                item.setOrderNo(o.getOrderNo());
                nos.add(item);
            });
        }
        orderBlock.setMessageOrderNo(nos);
        resp.setOrder(orderBlock);

        StoreDashboardResponse.WidgetOutline outline = new StoreDashboardResponse.WidgetOutline();
        outline.setSalesMoney(formatThousands(salesMoney));
        outline.setAll(orderPrice == null ? BigDecimal.ZERO : orderPrice);
        outline.setPercentage(calcPercentage(orderPrice, salesMoney));
        outline.setBalanceAll(balanceAll == null ? BigDecimal.ZERO : balanceAll);
        resp.setWidgetOutline(outline);

        StoreDashboardResponse.WidgetEcharts echarts = new StoreDashboardResponse.WidgetEcharts();
        echarts.setApplyNumber(applyNumber == null ? 0 : applyNumber);
        echarts.setOrderTotal(orderTotal == null ? 0 : orderTotal);
        echarts.setDeliveryOrderTotal(deliveryOrderTotal == null ? 0 : deliveryOrderTotal);
        resp.setWidgetEcharts(echarts);

        return resp;
    }

    private String formatThousands(BigDecimal value) {
        if (value == null) return "0";
        java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
        nf.setGroupingUsed(true);
        nf.setMaximumFractionDigits(0);
        return nf.format(value);
    }

    private String calcPercentage(BigDecimal orderPrice, BigDecimal salesMoney) {
        if (orderPrice == null || salesMoney == null || salesMoney.compareTo(BigDecimal.ZERO) <= 0) {
            return "0%";
        }
        BigDecimal hundred = new BigDecimal("100");
        BigDecimal percent = orderPrice.multiply(hundred).divide(salesMoney, 3, BigDecimal.ROUND_HALF_UP);
        if (percent.compareTo(hundred) > 0) {
            return "100%";
        }
        return percent.toPlainString() + "%";
    }

    private List<Long> getSpecifyUserIds(Long storeUserId) {
        // 对齐 PHP：
        // - 若角色为业务员(10007)：仅本人名下经销商
        // - 若角色为主管(10006)：本人及下级业务员名下经销商
        // - 其他：全量（或根据 DataScope）
        // 这里交由 XML 实现，若传入 null 则返回全量可见
        List<Long> ids = userMapper.getSpecifyUserIds(storeUserId);
        return CollUtil.defaultIfEmpty(ids, new ArrayList<>());
    }
}


